<template>
  <div class="address-edit-page">
    <van-nav-bar
      :title="isEdit ? '编辑地址' : '新增地址'"
      left-arrow
      @click-left="goBack"
      fixed
    />
    
    <div class="form-container">
      <div v-if="isLoading" class="loading-container">
        <van-loading type="spinner" color="#3490dc" />
        <span class="loading-text">加载中...</span>
      </div>
      
      <van-cell-group v-else inset class="form-group">
        <van-address-edit
          :area-list="areaList"
          :address-info="formData"
          :show-postal="true"
          :show-delete="isEdit"
          :show-set-default="true"
          @save="onSave"
          @delete="onDelete"
          @cancel="onCancel"
          :is-saving="isSaving"
          :is-deleting="isDeleting"
          :area-columns-placeholder="['请选择省', '请选择市', '请选择区']"
          show-area
          :validator="validator"
          :tel-maxlength="11"
          save-button-text="保存"
          delete-button-text="删除"
          tel-label="手机号码"
          address-label="详细地址"
          postal-label="邮政编码"
        />
      </van-cell-group>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { api } from '../network/api';
import { showToast, showDialog } from 'vant';
import { areaList } from '@vant/area-data';

// 定义API响应接口
interface ApiResponse {
  code: number;
  message: string;
  data?: any;
}

// 定义地址接口
interface Address {
  id: number;
  name: string;
  phone: string;
  provinceCode: string;
  provinceName: string;
  cityCode: string;
  cityName: string;
  districtCode: string;
  districtName: string;
  streetCode: string;
  streetName: string;
  detail: string;
  type: string;
  isDefault: boolean;
  postalCode?: string;
  userId?: string;
}

export default defineComponent({
  name: 'AddressEditView',
  
  setup() {
    const router = useRouter();
    const route = useRoute();
    const isSaving = ref(false);
    const isDeleting = ref(false);
    const isLoading = ref(false);
    const userId = ref<string>('');
    
    // 判断是编辑还是新增
    const addressId = computed(() => {
      const id = route.params.id;
      return id ? parseInt(id as string) : null;
    });
    
    const isEdit = computed(() => !!addressId.value);
    
    // 表单数据
    const formData = ref<Record<string, any>>({});
    
    // 获取用户ID
    const getUserId = () => {
      try {
        const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
        return userInfo.data?.userId || userInfo.data?.id || userInfo.userId || userInfo.id;
      } catch (e) {
        console.error('解析用户信息失败:', e);
        return '';
      }
    };
    
    // 获取地址详情
    const getAddressDetail = async () => {
      if (!addressId.value) {
        // 新增地址，设置空表单
        formData.value = {
          name: '',
          tel: '',
          province: '',
          city: '',
          county: '',
          addressDetail: '',
          areaCode: '',
          postalCode: '',
          isDefault: false
        };
        return;
      }
      
      try {
        isLoading.value = true;
        // 使用API接口获取所有地址，然后找到当前地址
        const response = await api.getUserAddresses(userId.value) as unknown as ApiResponse;
        
        if (response && response.code === 100) {
          const addressList = Array.isArray(response.data) ? response.data : [response.data];
          // 使用address_id或addressId查找地址
          const address = addressList.find((addr: any) => 
            addr.addressId === addressId.value || 
            addr.address_id === addressId.value || 
            addr.id === addressId.value
          );
          
          if (address) {
            // 转换为 Vant AddressEdit 需要的格式
            formData.value = {
              id: address.addressId || address.address_id || address.id,
              name: address.recipientName || address.recipient_name || address.name,
              tel: address.phone,
              province: address.province || address.provinceName,
              city: address.city || address.cityName,
              county: address.district || address.districtName,
              addressDetail: address.detailedAddress || address.detailed_address || address.detail,
              areaCode: address.districtCode || '',
              postalCode: address.postalCode || '',
              isDefault: Boolean(address.isDefault || address.is_default),
              userId: address.userId || address.user_id
            };
          } else {
            showToast('未找到该地址');
            router.back();
          }
        } else {
          showToast('获取地址详情失败');
          router.back();
        }
      } catch (error) {
        console.error('获取地址详情失败', error);
        showToast('获取地址详情失败');
        router.back();
      } finally {
        isLoading.value = false;
      }
    };
    
    // 删除地址
    const onDelete = async () => {
      if (!addressId.value) return;
      
      try {
        isDeleting.value = true;
        
        try {
          await showDialog({
            title: '提示',
            message: '确定要删除这个地址吗？',
            showCancelButton: true
          });
        } catch (e) {
          isDeleting.value = false;
          if (e === 'cancel') return; // 用户取消操作
          throw e;
        }
        
        const response = await api.deleteAddress(addressId.value, userId.value) as unknown as ApiResponse;
        console.log('删除地址API响应:', response);
        
        // 直接检查response.code
        if (response && response.code === 100) {
          showToast('删除成功');
          router.back();
        } else {
          showToast(response?.message || '删除地址失败');
          isDeleting.value = false;
        }
      } catch (error) {
        console.error('删除地址失败', error);
        showToast('删除地址失败');
        isDeleting.value = false;
      } finally {
        isDeleting.value = false;
      }
    };
    
    // 保存地址
    const onSave = async (content: any) => {
      try {
        // 检查 userId 是否存在
        if (!userId.value) {
          userId.value = getUserId();
          if (!userId.value) {
            showToast('获取用户信息失败，无法保存地址');
            return;
          }
        }

        isSaving.value = true;
        
        // 打印调试信息
        console.log('保存地址表单数据:', content);
        
        // 将Vant格式转换为API需要的格式
        const addressData = {
          recipientName: content.name,
          phone: content.tel,
          province: content.province,
          city: content.city,
          district: content.county,
          detailedAddress: content.addressDetail,
          isDefault: content.isDefault ? 1 : 0,
          userId: userId.value
        };
        
        // 打印调试信息
        console.log('转换后的地址数据:', addressData);
        
        let response;
        
        if (isEdit.value && addressId.value) {
          console.log(`更新地址 ID: ${addressId.value}`, addressData);
          // 更新地址
          response = await api.updateAddress(addressId.value, addressData) as unknown as ApiResponse;
        } else {
          console.log('新增地址:', addressData);
          // 新增地址
          response = await api.addAddress(addressData) as unknown as ApiResponse;
        }
        
        console.log('API响应:', response);
        
        // 直接检查response.code
        if (response && response.code === 100) {
          showToast('保存成功');
          setTimeout(() => {
            router.replace('/address');
          }, 500); // 延迟跳转，确保Toast能够显示
        } else {
          showToast(response?.message || '保存地址失败');
          console.error('保存地址失败:', response?.message);
          // 即使失败也结束加载状态
          isSaving.value = false;
        }
      } catch (error) {
        console.error('保存地址发生异常:', error);
        showToast('保存地址失败，请稍后重试');
        isSaving.value = false;
      } finally {
        isSaving.value = false;
      }
    };
    
    // 取消
    const onCancel = () => {
      router.back();
    };
    
    // 表单验证器
    const validator = (key: string, value: string) => {
      if (key === 'name' && !value) {
        return '请填写收货人姓名';
      }
      if (key === 'tel' && !/^1[3-9]\d{9}$/.test(value)) {
        return '请填写正确的手机号码';
      }
      if (key === 'addressDetail' && !value) {
        return '请填写详细地址';
      }
      if (key === 'areaCode' && !value) {
        return '请选择地区';
      }
      return '';
    };
    
    // 返回上一页
    const goBack = () => {
      router.back();
    };
    
    // 页面初始化
    onMounted(() => {
      // 获取用户ID
      userId.value = getUserId();
      if (!userId.value) {
        showToast('获取用户信息失败');
        router.back();
        return;
      }
      
      // 获取地址详情
      getAddressDetail();
    });
    
    return {
      isEdit,
      formData,
      areaList,
      isSaving,
      isDeleting,
      isLoading,
      onSave,
      onDelete,
      onCancel,
      validator,
      goBack,
      userId
    };
  }
});
</script>

<style scoped>
.address-edit-page {
  background-color: #f7f8fa;
  min-height: 100vh;
}

.form-container {
  padding-top: 46px;
}

.form-group {
  margin-top: 12px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  margin-top: 50px;
}

.loading-text {
  margin-top: 10px;
  color: #666;
}

/* 覆盖Vant组件样式 */
:deep(.van-address-edit) {
  padding-top: 0;
}

:deep(.van-address-edit__buttons) {
  padding: 30px 15px;
}

:deep(.van-button--primary) {
  background-color: #3490dc;
  border-color: #3490dc;
}
</style> 